package com.lagou.homework.test01;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {

    /**
     * 声明数据库的驱动类, URL, 用户名, 密码
     */
    public static  String DRIVER_CLASS;
    public static  String URL;
    public static  String USERNAME;
    public static  String PASSWORD;

    static {

        try {

            /**
             * 获取properties文件的内容
             */
            InputStream inputStream = JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties");

            Properties p = new Properties();
            // 加载配置文件内容
            p.load(inputStream);

            // 获取配置文件的配置项并赋值给类静态变量
            DRIVER_CLASS = p.getProperty("driverClassName");
            URL = p.getProperty("url");
            USERNAME = p.getProperty("username");
            PASSWORD = p.getProperty("password");

            /**
             * 注册驱动  这一步可以省略
             */
            Class.forName(DRIVER_CLASS);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 使用DriverManager类获取数据库连接
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {

        return DriverManager.getConnection(URL, USERNAME, PASSWORD);
    }

    /**
     * 关闭资源
     * @param conn
     * @param statement
     * @throws SQLException
     */
    public static void close(Connection conn, Statement statement) throws SQLException {

        if (null != conn && null != statement) {
            statement.close();
            conn.close();
        }
    }

    /**
     * 关闭资源
     * @param conn
     * @param statement
     * @param resultSet
     * @throws SQLException
     */
    public static void close(Connection conn, Statement statement, ResultSet resultSet) throws SQLException {

        if (null != conn && null != statement && null != resultSet) {
            resultSet.close();
            statement.close();
            conn.close();
        }
    }
}
